package com.zhang.mqtt.config;

import com.zhang.mqtt.properties.MqttProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

/**
 * @Author 超chao
 * @Description 配置MqttOutBound  发送消息
 * @Date 2025/7/24/周四 15:52
 * @Version 1.0
 */
@Configuration
public class MqttOutBoundConfiguration {
    @Autowired
    private MqttProperties mqttProperties;
    @Autowired
    private MqttPahoClientFactory mqttPahoClientFactory;
    // 消息通道
    @Bean
    public MessageChannel messageOutboundChannel() {
        return new DirectChannel();
    }

    @Bean
    @ServiceActivator(inputChannel = "messageOutboundChannel")
    public MessageHandler messageOutboundHandler() {
        MqttPahoMessageHandler mqttPahoMessageHandler = new MqttPahoMessageHandler(
                mqttProperties.getBroker(),
                mqttProperties.getPubClientId(),
                mqttPahoClientFactory

                );
        mqttPahoMessageHandler.setDefaultQos(0);
        mqttPahoMessageHandler.setAsync(true);
        mqttPahoMessageHandler.setDefaultTopic("default");
        return mqttPahoMessageHandler;
    }
}
